<?php

defined('BASEPATH') or die('forbidden');

class Area_Controller Extends Controller {
    #public $act_cfg;
    private $wholeServerHost;
    public $statelist = array();
    public $modelist = array();
    private $server_list;  //区号列表

    function _init() {
        check_level(50, segment(0), segment(1), segment(2, 'index'));

        $config = get_config();
        $this->wholeServerHost = $config['host_url'];

        //SS_Ready     = 1 //未开放
        //SS_NewSvr    = 2 //新服
        //SS_Good      = 3 //流畅
        //SS_Busy      = 4 //拥挤
        //SS_Maintain  = 5 //维护
        //SS_Full      = 6 //爆满
        //SS_Recommend = 7 //推荐
        //SS_Close     = 8 //关闭

        $this->statelist = array(
            '2' => translate('AREA_STATUS_NEW'), 
            '3' => translate('AREA_STATUS_GOOD'),
            '6' => translate('AREA_STATUS_FULL'),
            '7' => translate('AREA_STATUS_RECOMMEND'),
            '5' => translate('AREA_STATUS_MAINTNCE'),
            '1' => translate('AREA_STATUS_WAIT'),
            '8' => translate('AREA_STATUS_CLOSE'),
        );

        $this->modelist = array(
            '0' => translate('SVR_MODE_RELEASE'),
            '1' => translate('SVR_MODE_DEBUG'),
        );

        $this->server_list=get_server_list();
        //$this->flaglist = array( '0' => translate('AREA_FLAG_NEW') , '1' => translate('AREA_FLAG_SUGGEST'),'2'=>  translate('AREA_FLAG_NULL'));
        $this->view->assign("statelist", $this->statelist);
        $this->view->assign("modelist", $this->modelist);
        //$this->view->assign("flaglist", $this->flaglist);
    }

    function index() {
        $this->view->display("area/area/index");
    }

    function flexigrid() {
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();

        $pd['SessionID']="ewewqw";
        $pd['SessionKey']="wqqew";

        date_default_timezone_set("PRC");
        $data=array();

        foreach ($this->server_list as $k=>$v){
            $pd['SvrID'] = (int)$v['SvrID'];

            $row2 =vpost($this->wholeServerHost.'gm_get_gamesvr_time',3,json_encode($pd));
            //$row2 =vpost('http://192.168.100.240:8080/gm_get_gamesvr_time',3,json_encode($pd));
            $rows2=json_decode($row2,true);

            $vd["SvrID"] = $v['SvrID'];
            $vd["SvrState"] = $v['SvrState'];
            $vd["SvrMode"] = $v['SvrMode'];
            $vd["SvrOutAddr"] = $v['SvrAddr'];
            $vd['SvrName1'] = $v['SvrName'][0];
            $vd['SvrName2'] = $v['SvrName'][1];
            $vd['SvrName3'] = $v['SvrName'][2];

            //$v['SvrOpenTime'] = get_datetime($v['SvrOpenTime']);
            $vd['SvrOpenTime'] = get_datetime($rows2['SvrOpenTime']);
            $vd['SvrCurTime'] = get_datetime($rows2['CurTime']);
            //$V['SvrMode'] = $rows2['SvrMode'];
            $data[$k]=array('id' => $vd['SvrID'], 'cell' => $vd);
        }

        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $data
        );
        echo json_encode($result);
    }

    function add($id = 0) {
        if (is_submit()) {
            $rowdata = $_POST['row'];
            //$rowdata['version'] = addslashes(json_encode(explode("/r/n", $rowdata['version'])));
            $rowdata['host'] = get_full_url($rowdata['host']);
            $rowdata['opentime'] = $rowdata['opentime'] ? strtotime($rowdata['opentime']) : 0;
            $one = $this->db->one("SELECT * FROM {pre}areasample WHERE id='{$rowdata['id']}'");
            if (is_array($one))
                error(translate('C_EXISTED_PARAM_ID', $rowdata['id']));
            
            include_once CONFIGPATH."config.php";
            
            $rowdata['id']=(int)$rowdata['id'];
            $rowdata['opentime']=  (int)$rowdata['opentime'];
            $rowdata['state']=(int)$rowdata['state'];
            $rowdata['flag']=(int)$rowdata['flag'];
            $rows[] = $rowdata;
            $list['arealist'] = $rows;
            $jsonStr = json_encode($list);
            //$result = vpost($this->wholeServerHost."areas=$jsonStr&action=47");
            //if($result){
            //    $id = $this->db->insert("{pre}areasample", $rowdata);
            //    $this->db->query("UPDATE {pre}areasample SET weigh=id WHERE id='{$id}'");
                //$rowdata['host_url'] = dirname(base_url(1)) . '/api/';
                //set_async_area($rowdata['id'], 'area/area/edit', $rowdata);
            //    insert_log(translate('MENU_AREA_AREA'),translate('ADD'), null,$id);
             //   cp_tips("success", $id);
            //}else{
            //    cp_tips("error", $id);
            //}
        }
        $lastarea = $this->db->one("SELECT * FROM {pre}areasample ORDER BY weigh DESC");
        if ($lastarea) {
            $lastarea['idarr'] = explode(":", $lastarea['id']);
            $lastarea['hostarr'] = explode(":", $lastarea['host']);
        }
        $this->view->assign("lastarea", $lastarea);

        $this->view->display("area/area/add");
    }

    function edit($id = 0) {
        if ($id === 0){
            error(translate('C_INVALID_PARAM_ID', $id));
        }

        $data=array();
        if (!is_array($data)){
            error(translate('C_INVALID_PARAM_ID', $id));
        }

        if (is_submit()) {
            $rowdata = $_POST['row'];
            $pd['SessionID']="ewewqw";
            $pd['SessionKey']="wqqew";

            $pd['OpenTime'] = $rowdata['svropentime'] ? strtotime($rowdata['svropentime']) : 0;
            $pd['SvrID']=(int)$rowdata['svrid'];

            $pd['SvrName'] = array();
            array_push($pd['SvrName'] , $rowdata['svrname1']);
            array_push($pd['SvrName'] , $rowdata['svrname2']);
            array_push($pd['SvrName'] , $rowdata['svrname3']);

            $pd['SvrOuterAddr']=$rowdata['svroutaddr'];
            $pd['SvrInnerAddr']=$rowdata['svroutaddr'];
            $pd['State']=(int)$rowdata['state'];
            $pd['SvrMode'] = (int)$rowdata['smode'];
            $pd['SvrDefault']=0;
            $pd['ControlFlag']=0;
            $result = vpost($this->wholeServerHost.'gm_set_server_state', 3, json_encode($pd));
            $code=json_decode($result,true);
            if($code['RetCode']==0){
                //$this->db->update("{pre}areasample", $rowdata, array('id' => $id));
                insert_log(translate('MENU_AREA_AREA'),translate('EDIT'), $rowdata, $rowdata);
            }else{
                cp_tips("error", $id);
            }

            // 设置游戏服务器系统时间
            $pd2['SessionID']="ewewqw";
            $pd2['SessionKey']="wqqew";
            $pd2['Time'] = (string)$rowdata['svrcurtime'];
            $pd2['SvrOpenTime'] = strtotime($rowdata['svropentime']);
            $pd2['SvrID'] = (int)$rowdata['svrid'];
            $strResult = vpost($this->wholeServerHost.'gm_modify_sys_time', 3, json_encode($pd2));
            $code2=json_decode($strResult,true);
            //操作失败或者连接失败
            if($code2['RetCode'] == 0)
            {
                insert_log(translate('MENU_SEND_OBJECT'),translate('ADD'),NULL,$rowdata);
                //echo "<script>alert('".translate('C_TIPS_SUCCESS_TEXT')."')</script>";
                cp_tips("success", $id);
            }
            else
            {
                unset($rowdata);
                //echo "<script>alert('".translate('C_TIPS_ERROR_TEXT')."')</script>";
                cp_tips("error", $id);
            }
        }

        date_default_timezone_set("PRC");

        $pd['SessionID']="ewewqw";
        $pd['SessionKey']="wqqew";
        $pd['SvrID'] = (int)$id;

        $row2 =vpost($this->wholeServerHost.'gm_get_gamesvr_time',3,json_encode($pd));
        $rows2=json_decode($row2,true);

        $this->view->assign("svrname1", $v['SvrName'][0]);
        $this->view->assign("svrname2", $v['SvrName'][1]);
        $this->view->assign("svrname3", $v['SvrName'][2]);
        $this->view->assign("svroutaddr", $v['SvrOutAddr']);
        $this->view->assign('svropentime', date('Y-m-d H:i:s', $rows2['SvrOpenTime']));
        $this->view->assign('svrcurtime', date('Y-m-d H:i:s', $rows2['CurTime']));

        $this->view->assign("svrid", (int)$id);
        $this->view->assign("statelist", $this->statelist);
        $this->view->assign("modelist", $this->modelist);
        
        $this->view->display("area/area/edit", array('row' => $data));
    }

    function maintain($id = 0){
        if ($id === 0)
            error(translate('C_INVALID_PARAM_ID', $id));
        $data=array();
        //$post_data='{"SessionID":"","SessionKey":""}';
        //$row = vpost($this->wholeServerHost.'gm_server_list',3,$post_data);
        //$rows=json_decode($row,true);
        //foreach ($rows['SvrList'] as $k=>$v){
        foreach ($this->server_list as $k=>$v){
            if($v['SvrID'] == $id){
                $data=$v;
            }
        }
        //var_dump($data);
        if (!is_array($data))
            error(translate('C_INVALID_PARAM_ID', $id));

        if (is_submit()) {
            $rowdata = $_POST['row'];
            var_dump($_POST['row']);
            //$rowdata['version'] = addslashes(json_encode(explode("/r/n", $rowdata['version'])));
            $maintain_data['SessionID'] = "ewewqw";
            $maintain_data['SessionKey'] = "wqqew";
            $maintain_data['SvrID'] = (int)$rowdata['SvrID'];
            $maintain_data['SvrName'] = $rowdata['SvrName'];
            $maintain_data['SvrStatus'] = (int)$rowdata['SvrState'];
            $maintain_data['SvrNotice'] = $rowdata['SvrNotice'];
            $jsonStr = json_encode($maintain_data);
            //var_dump($maintain_data);

            $result = vpost($this->wholeServerHost.'set_server_info', 3, $jsonStr);
            $code = json_decode($result, true);
            if ($code['RetCode'] == 0) {
                //$this->db->update("{pre}areasample", $rowdata, array('id' => $id));
                insert_log(translate('MENU_AREA_AREA'), translate('MAINTAIN'), $row, $rowdata);
                cp_tips("success", $id);
            } else {
                cp_tips("error", $id);
            }
        }
        $this->view->display("area/area/maintain", array('row' => $data));
    }

    function del($id = 0) {
        $c = 0;
        $r = '';
        if ($id === 0)
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        $row = $this->db->one("SELECT * FROM {pre}areasample WHERE id='{$id}'");
        if (!is_array($row))
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        if ($this->db->delete('{pre}areasample', array('id' => $id))) {
            insert_log(translate('MENU_AREA_AREA'),translate('DEL'), array('id'=> $id));
            $c = 1;
        } else {
            $r = translate('C_TIPS_ERROR_TEXT');
        }
        json_output($c, $r);
    }

    function multi() {
        $type = $this->input->post("type");
        $ids = $this->input->post("ids");
        $c = 0;
        $r = '';
        $allids = $ids = explode(',', $ids);
        if (count($ids) == 0) {
            $r = translate('C_INVALID_PARAMS');
        } else {
            $ids = "'" . implode("','", $ids) . "'";
            if ($type == 'delete') {
                $this->db->query("DELETE FROM {pre}areasample WHERE id IN ({$ids})");
                insert_log(translate('MENU_AREA_AREA'),translate('MULTI_DEL'), array('ids'=> implode(",", $allids)));
                $c = 1;
            } else if ($type == 'accept') {
                $this->db->query("UPDATE {pre}areasample SET state='normal' WHERE id IN ({$ids})");
                insert_log(translate('MENU_AREA_AREA'),translate('OPEN'), array('ids'=> implode(",", $allids)));
                $c = 1;
            } else if ($type == 'reject') {
                $this->db->query("UPDATE {pre}areasample SET state='close' WHERE id IN ({$ids}) AND state!='hide'");
                insert_log(translate('MENU_AREA_AREA'),translate('CLOSE'), array('ids'=> implode(",", $allids)));
                $c = 1;
            } else if ($type == 'new') {
                $this->db->query("UPDATE {pre}areasample SET state='new' WHERE id IN ({$ids})");
                insert_log(translate('MENU_AREA_AREA'),translate('MULTI_OPEN'), array('ids'=> implode(",", $allids)));
                $c = 1;
            } else {
                $r = translate('C_INVALID_PARAMS');
            }
        }
        json_output($c, $r);
    }
}